from datetime import datetime

from flask import request, jsonify
from passlib.hash import pbkdf2_sha256
import sys
sys.path.append("..")
from models import UserMsg
from utils import JWT,Serialize

def defineUserViews(app,db):
    @app.route('/api/home/about',methods=['POST'])
    def userAbout():
        user_id = JWT.get_parse_token(request)
        # 获取数据库的数据
        userinfo = UserMsg.query.filter_by(id=user_id).first()
        data = Serialize.serialize_models(userinfo)
        return jsonify ({"msg": "获取用户信息成功！","data":data, "code":200})

    @app.route('/api/home/update',methods=["POST"])
    def userUpdate():
        # 获取请求的数据
        input = request.form
        email = input.get("email")
        name = input.get("name")
        user_id = JWT.get_parse_token(request)
        # 更新数据库的数据
        obj = db.session.query (UserMsg).filter_by (id=user_id)[0]
        obj.email = email
        obj.name = name
        obj.update_time = datetime.now()
        db.session.commit ()
        return jsonify ({"msg": "更新用户信息成功！", "code":200})

    @app.route('/api/home/password',methods=["POST"])
    def userPwd():
        # 获取请求的数据
        input = request.form
        old_password = input.get("old_password")
        new_password = input.get("new_password")
        user_id = JWT.get_parse_token(request)
        # 验证旧密码
        obj = db.session.query (UserMsg).filter_by (id=user_id)[0]
        if not pbkdf2_sha256.verify(old_password,obj.password):
            return jsonify({"msg":"修改失败！原密码错误","code":403})
        # 更新数据
        obj.password = pbkdf2_sha256.hash(new_password)
        obj.update_time = datetime.now()
        db.session.commit ()
        return jsonify ({"msg": "修改密码成功！", "code":200})